from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from matplotlib import pyplot as plt
from .models import Data_date, Access_ip
import matplotlib, numpy as np
import io,base64
from datetime import datetime, timedelta

#一些配置
matplotlib.use('Agg')  # 使用非交互式后端
# 配置 matplotlib 中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体字体
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示为方块的问题
plt.rcParams['toolbar'] = 'None'# 关闭工具栏


# Create your views here.
#----监控页面----
def monitor(request):
    return render(request, 'monitor.html')

#----功能接口----
def get_total(request):
    try:
        #从数据库获取数据
        today = datetime.now().date()
        data_7_bef = today - timedelta(days=7)
        
        # 使用select_related优化查询，避免递归
        date7 = Data_date.objects.filter(
            date__gte=data_7_bef, 
            date__lte=today
        ).order_by('date').select_related()
        
        dates = [d.date for d in date7]  # 提取日期
        dates.sort()
        
        # 使用更高效的查询方式
        counts = []
        for d in date7:
            count = Access_ip.objects.filter(date=d).count()
            counts.append(count)
        # 生成图片
        if not dates or not counts:
            # 如果没有数据，创建一个空图表
            fig, ax = plt.subplots(figsize=(6, 4))
            ax.text(0.5, 0.5, '暂无数据', ha='center', va='center', fontsize=14)
            ax.set_xlim(0, 1)
            ax.set_ylim(0, 1)
        else:
            fig, ax = plt.subplots(figsize=(6, 4))  # 设置较小的图表尺寸
            fig.patch.set_facecolor("#FFFFFFFF")   # 画布背景
            ax.set_facecolor("#FFFFFFFF")          # 坐标轴背景
            bar = ax.bar(dates, counts, color="#5238AF", label='访问量', alpha=0.8)# 柱状图
            ax.set_title('过去7天的访问量', fontsize=14, fontweight='bold', pad=20)
            ax.set_ylabel('访问量', fontsize=12)
            ax.set_xlabel('日期', fontsize=12)
            ax.set_xticks(dates)# 设置X轴刻度
            ax.set_xticklabels(dates, rotation=40, ha='right')# 设置X轴刻度标签
            ax.legend(loc='best')  # 自动选择最佳图例位置
            if counts:
                ax.set_ylim(0, max(counts) * 1.1)  # 增加10%的上边距
            plt.tight_layout()# 自动调整子图参数，使之填充整个图像区域
        # 保存图片到内存
        buffer = io.BytesIO()
        plt.savefig(buffer, format='png', bbox_inches='tight', dpi=150, facecolor="#FFFFFFFF")
        buffer.seek(0)
        image_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
        buffer.close()
        plt.close()
        
        #获取今天的访问量
        try:
            data_today = Data_date.objects.get(date=today)
            ips_today = Access_ip.objects.filter(date=data_today)
            today_list = {}
            for ip_obj in ips_today:
                ip_address = ip_obj.ip_address
                if ip_address not in today_list:
                    today_list[ip_address] = 1
                else:
                    today_list[ip_address] += 1
            today_list = sorted(today_list.items(), key=lambda x: x[1], reverse=True)[:5]# 取前5个
            today_data = [{'ip': ip, 'count': count} for ip, count in today_list]# 转换为字典列表
        except Data_date.DoesNotExist:
            today_data = []  # 如果今天没有数据，返回空列表
        return JsonResponse({
            'message': '获取成功',
        'image_base64': image_base64,
        'today_data': today_data
        },status=200)
    except Exception as e:
        return JsonResponse({'error': f'获取失败: {str(e)}'}, status=500)